# 此接口用于从orthanc数据库中获取一个study的所有模态（series）数据，并转换为numpy格式，拼接成list
from pyorthanc import find, Orthanc
import numpy as np
import os

# 数据库连接
orthanc = Orthanc('http://localhost:8042',
                  username='orthanc', password='orthanc')

# 输入为病人的id和study_id，其中study_id为唯一标识，模态默认MR，
# 根据两个id在数据库中筛选出特定病人的特定study，然后将其三个模态的数据存储为一个list,送入分割算法

def get_list_from_Orthanc(patient_id,study_id,modality='MR'):
    patients = find(
        orthanc=orthanc,
        # Optional: filter with pyorthanc.Series object
        series_filter=lambda s: s.modality == modality  #找到所有包含MR模态的的数据，这样可以过滤掉后续的seg文件，只使用MR文件
    )
    study_list=[]
    # 这块可以优化一下，如果数据库很庞大搜索时间会长 
    # 异常处理未实现：如果搜索不到id，应该要弹出查找失败
    for patient in patients:
        # patient.get_zip()  # DICOM files' content in bytes
        if patient.id_ == patient_id:
          for study in patient.studies:
              if study.id_ == study_id:
                  for series in study.series: 
                      flag=0
                      for instance in series.instances:
                        # Retrieve the DICOM file and make a pydicom.FileDataset
                        pydicom_dataset = instance.get_pydicom()
                        # You can access the pydicom.FileDataset attribute
                        arr = pydicom_dataset.pixel_array
                        # 数组拼接成3D
                        arr = np.expand_dims(arr, axis=0)
                        if flag == 0:
                            array = arr
                            flag += 1
                            continue
                        array = np.concatenate((array, arr), axis=0)
                      study_list.append(array)
    print(study_list)
    return study_list

if __name__ == '__main__':
    patient_id='b26feadf-13887444-44731978-584920b0-4cc20110'
    study_id='4afc4049-efa21a22-8ffaff60-73f9253d-b10e8395'
    study_list=get_list_from_Orthanc(patient_id,study_id)
    print('finish')
